<!-- 概率地震易损性分析 -->
<template>
	<div class="app-container">
		<el-form :inline="true" ref="queryRef" label-position="right" :model="params" label-width="200px">
			<div class="form-inline">
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="维护人：" class="form-item" prop="userName"><el-input v-model="params.userName"
								placeholder="请输入" clearable /></el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="维护时间:">
							<el-col :span="11">
								<el-form-item prop="startTime">
									<el-date-picker clearable v-model="params.startTime" type="date" placeholder="开始时间"
										value-format="YYYY-MM-DD" :disabled-date="startDisableDate" style="width: 100%" />
								</el-form-item>
							</el-col>
							<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
							<el-col :span="11">
								<el-form-item prop="endTime">
									<el-date-picker clearable v-model="params.endTime" type="date" placeholder="结束时间"
										value-format="YYYY-MM-DD" :disabled-date="endDisableDate" style="width: 100%" />
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<!-- <el-col :span="11">
						<el-form-item label="维护人所属单位：" class="form-item" prop="maintainerUnit"><el-input
								v-model="params.maintainerUnit" placeholder="请输入" clearable /></el-form-item>
					</el-col> -->
					<el-col :span="11">
						<el-form-item label="结构类型：">
							<el-col :span="12">
								<el-form-item prop="structureType0">
									<el-select v-model="params.structureType0" placeholder="请选择" class="form-select"
										@change="structureTypeChange" clearable>
										<el-option v-for="item in structureTypeOptions" :key="item.value"
											:label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
							<el-col :span="11">
								<el-form-item prop="structureType1">
									<el-select v-model="params.structureType1" placeholder="请选择" class="form-select"
										clearable>
										<el-option v-for="item in structureType1Options" :key="item.value"
											:label="item.label" :value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="用途：">
							<el-col :span="12">
								<el-form-item prop="purpose0">
									<el-select v-model="params.purpose0" placeholder="请选择" class="form-select"
										@change="useChange" clearable>
										<el-option v-for="item in useOptions" :key="item.value" :label="item.label"
											:value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
							<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
							<el-col :span="11">
								<el-form-item prop="purpose1">
									<el-select v-model="params.purpose1" placeholder="请选择" class="form-select" clearable>
										<el-option v-for="item in use1Options" :key="item.value" :label="item.label"
											:value="item.value"></el-option>
									</el-select>
								</el-form-item>
							</el-col>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="区域：" class="form-item" prop="region">
							<el-form-item prop="province" style="width:120px;margin-right:10px;">
								<el-select v-model="params.province" placeholder="请选择省" @change="chooseProvince" clearable
									value-key="id">
									<el-option v-for="item in provinceData" :key="item.id" :label="item.name"
										:value="item"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="city" style="width:120px;margin-right:10px;">
								<el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable
									value-key="id">
									<el-option v-for="item in cityData" :key="item.id" :label="item.name"
										:value="item"></el-option>
								</el-select>
							</el-form-item>
							<el-form-item prop="county" style="width:120px;">
								<el-select v-model="params.county" placeholder="请选择县" @change="chooseCounty" clearable
									value-key="id">
									<el-option v-for="item in areaData" :key="item.id" :label="item.name"
										:value="item"></el-option>
								</el-select>
							</el-form-item>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="设防情况：" class="form-item" prop="fortification">
							<el-select v-model="params.fortification" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label"
									:value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="年代：" class="form-item" prop="years">
							<el-select v-model="params.years" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
									:value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="11" v-if="!isAdmin"></el-col>
					<el-col :span="11">
						<el-form-item label="是否在基础库：" class="form-item" prop="basicLibrary" v-if="isAdmin">
							<el-select v-model="params.basicLibrary" placeholder="请选择" class="form-select" clearable>
								<el-option v-for="item in basicLibraryOptions" :key="item.value" :label="item.label"
									:value="item.value"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>
				<el-row justify="end">
					<el-form-item class="bottom-button">
						<el-button type="primary" @click="onSearch">查询</el-button>
						<el-button type="primary" @click="onRest">重置</el-button>
					</el-form-item>
				</el-row>
			</div>
		</el-form>

		<div class="table-wrapper">
			<el-table class="listTable" ref="multipleTableRef" border :data="tableData" style="width: 100%"
				@selection-change="handleSelectionChange" @row-click="rowClick"
				:cell-style="{ border: '1px solid #e5ebf7' }"
				:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
				<el-table-column type="selection" width="55" label="序号" />
				<el-table-column prop="number" header-align="center" align="center" label="编号">
					<template #default="scope">
						<el-button link type="text" size="small" @click.prevent="viewProject(scope.row)">{{ scope.row.number
						}}</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="region" header-align="center" align="center" label="区域" />
				<el-table-column prop="st" header-align="center" align="center" label="结构类型" />
				<el-table-column prop="years" header-align="center" align="center" label="年代" width="100" />
				<el-table-column prop="fortification" header-align="center" align="center" label="设防情况" width="100" />
				<el-table-column prop="calculateOrNot" header-align="center" align="center" label="是否已计算" width="100">
					<template #default="scope">
						<span v-if="scope.row.calculateOrNot == '1'">是</span>
						<span v-else>否</span>
					</template>
				</el-table-column>
				<el-table-column prop="userName" header-align="center" align="center" label="维护人" width="120" />
				<el-table-column prop="createTime" header-align="center" align="center" label="维护时间" width="160">
					<template #default="{ row }">
						<span v-if="row.createTime">{{ proxy.parseTime(row.createTime) }}</span>
					</template>
				</el-table-column>
				<el-table-column prop="use" header-align="center" align="center" label="用途">
					<template #default="{ row }">
						{{ getUseByOptions(row.purpose0) }}
						<span v-if="row.purpose0 && row.purpose1">-</span>
						{{ getChildUseByOptions(row.purpose0, row.purpose1) }}
					</template>
				</el-table-column>
				<el-table-column prop="basicLibrary" header-align="center" align="center" label="是否在基础库" width="120"
					v-if="isAdmin">
					<template #default="{ row }">{{ row.basicLibrary === '1' ? '是' : '否' }}</template>
				</el-table-column>
				<el-table-column label="操作" fixed="right" align="center" width="120" v-if="isAdmin">
					<template #default="{ row }">
						<el-button :type="row.basicLibrary && row.basicLibrary.trim() == '1' ? 'danger' : 'success'" text
							size="small" @click="handleRemove(row)">
							{{ row.basicLibrary === '1' ? '移出基础库' : '移入基础库' }}
						</el-button>
						<!-- <el-button type="text" size="small" @click="onDelete(row)">删除</el-button>
						<el-button type="text" size="small" @click="onModify(row)">修改</el-button> -->
					</template>
				</el-table-column>
			</el-table>
			<div class="paging">
				<el-pagination background v-model:current-page="queryPagination.pageNo" :layout="layout"
					:page-size="queryPagination.pageSize" :total="queryPagination.total"
					:page-sizes="queryPagination.arrSize" @current-change="handleCurrentChange"
					@size-change="handleSizeChange" />
			</div>
		</div>
	</div>
</template>

<script setup>
import { reactive, toRefs } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'
// 引入接口
import {
	queryCpvAnalysisApi, //分页查询
	moveBasicLibraryApi, //移入/出基础库
} from '@/api/buildingVulnerAnalysis/buildingVulnerAnalysis.js';
import { getProvince, getChildArea } from '@/api/system/division';
// 引入store
import useUserStore from '@/store/modules/user';
import useDictStore from '@/store/modules/dict';
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 是否管理员
const isAdmin = computed(() => userStore.isAdmin || false);
// 用户名
const userName = computed(() => userStore.name || '');
// 所属机构名称
const orgName = computed(() => userStore.orgName || '');

// 获取当前实例
const { proxy } = getCurrentInstance();
// 全局路由对象
const router = useRouter();

const data = reactive({
	// 表单参数
	params: {
		// userName: userName.value, //维护人
		// maintainerUnit: orgName.value, //维护人所属单位
		userName: '', //维护人
		maintainerUnit: '', //维护人所属单位
		startTime: '', //维护开始时间
		endTime: '', //维护结束时间
		structureType0: '', //结构类型
		structureType1: '',
		fortification: '', //设防情况
		years: '', //年代
		region: '', //区域
		purpose0: '', //用途
		purpose1: '',
		province: '', //省
		city: '', //市
		county: '',//区县
		basicLibrary: ''//是否在基础库
	},
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	// 年份
	yearsOptions: dictStore.yearsOptions || [],
	//是否在基础库
	basicLibraryOptions: dictStore.basicLibraryOptions || [],
	// 结构类型
	structureTypeOptions: dictStore.structureTypeOptions || [],
	structureType1Options: [],
	// 用途
	useOptions: dictStore.useOptions || [],
	use1Options: [],
	// 表格
	tableData: [],
	// 表格选中数据
	multipleSelection: [],
	// 当前行数据
	curTableRow: {},

	// 分页面板控件
	layout: ' prev, pager, next, jumper, sizes, total',
	// 分页参数
	queryPagination: {
		pageNo: 1,
		pageSize: 10,
		total: 100,
		arrSize: [10, 20, 50, 100, 200, 500, 1000],
	}
});

const {
	// 表单参数
	params,
	// 烈度选项
	intensityOptions,
	// 设防情况选项
	fortificationOptions,
	// 年代选项
	yearsOptions,
	//是否在基础库
	basicLibraryOptions,
	// 结构类型选项
	structureTypeOptions,
	structureType1Options,
	// 用途选项
	useOptions,
	use1Options,
	// 表格数据
	tableData,
	// 表格选中数据
	multipleSelection,
	// 当前行数据
	curTableRow,
	// 分页数据
	queryPagination,
	// 分页工具栏
	layout
} = toRefs(data);

/* 
	根据值获取用途
	params: {
		key: 值
	}
 */
function getUseByOptions(key) {
	const use = useOptions.value.find(item => item.value == key);
	return use ? (use.label || '') : '';
}
/* 
	根据值获取子用途
	params: {
		key1: 一级值
		key2: 二级值
	}
 */
function getChildUseByOptions(key1, key2) {
	const use = useOptions.value.find(item => item.value == key1);
	let childUse = {};
	if (use && use.children) {
		childUse = use.children.find(item => item.value == key2);
	}
	return childUse ? (childUse.label || '') : '';
}

// 行政区划
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
/** 获取省列表 */
function getProvinceData() {
	getProvince().then(response => {
		provinceData.value = response.data;
	});
}
// 选择省份
function chooseProvince(value) {
	params.value.city = null;
	params.value.county = null;
	params.value.province = value.name;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value.id).then(response => {
		cityData.value = response.data;
	});
}
// 选择城市
function chooseCity(value) {
	params.value.city = value.name;
	params.value.county = null;
	areaData.value = [];
	getChildArea(value.id).then(response => {
		areaData.value = response.data;
	});
}
// 选择区县
function chooseCounty(value) {
	params.value.county = value.name;
}

// 开始时间禁用区间
const startDisableDate = time => {
	let endDateVal = params.value.endTime;
	if (endDateVal) {
		return time.getTime() > new Date(endDateVal).getTime();
	}
};
// 结束时间禁用区间
const endDisableDate = time => {
	let beginDateVal = params.value.startTime;
	if (beginDateVal) {
		return time.getTime() < new Date(beginDateVal).getTime();
	}
};

// 结构类型选择
const disabledcs = ref(false);
const structureTypeChange = val => {
	const structureTypes = structureTypeOptions.value.find(item => item.value === val);
	if (structureTypes) {
		structureType1Options.value = structureTypes.children;
	}
	params.value.structureType1 = '';
	// 清空用途
	params.value.purpose0 = '';
	params.value.purpose1 = '';
	use1Options.value = [];
	// 设防情况
	params.value.fortification = '';
	fortificationOptions.value = dictStore.fortificationOptions;
	// 年代
	yearsOptions.value = dictStore.yearsOptions;
	// 过滤楼层预选项
	if (val=='钢筋混凝土结构'||val=='钢结构') {
		// csOptions.value = dictStore.csOptions;
		disabledcs.value = false;
		// 用途处理
		useOptions.value = dictStore.useOptions;
	} else if(val=='组合结构'){
		// 层数处理
		// csOptions.value = dictStore.csOptions.filter((item, index) => index == 2);
		// params.value.cs = ''
		disabledcs.value = false;
		// 用途处理
		useOptions.value = [
            {
                value: '第Ⅰ类',
                label: '第Ⅰ类',
                children: [
                    {
                        value: '住宅',
                        label: '住宅'
                    },
                    {
                        value: '公寓',
                        label: '公寓'
                    },
                    {
                        value: '学生和职工集体宿舍',
                        label: '学生和职工集体宿舍'
                    },
                    {
                        value: '宾馆',
                        label: '宾馆'
                    },
                    {
                        value: '招待所',
                        label: '招待所'
                    },
                    {
                        value: '其他人员居住场所',
                        label: '其他人员居住场所'
                    }
                ]
            },
            {
                value: '第Ⅱ类',
                label: '第Ⅱ类',
                children: [
                    {
                        value: '办公室',
                        label: '办公室'
                    },
                ]
            },
        ]
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value!='未设防'&&item.value!='自设防'));
	}else if(val=='砌体结构'){
		// 层数处理
		// csOptions.value = dictStore.csOptions.filter((item, index) => index < 2);
		disabledcs.value = false;
		// 切换类型时，部分类型楼层没有就"9层以上"选项，则清空
		// if (params.value.cs == '9层以上') {
		// 	params.value.cs = ''
		// }
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions;
	}else{
		// 层数处理
		disabledcs.value = true;
		// csOptions.value = [];
		// params.value.cs = ''
		// 用途
		if(val=='土木结构'||val=='木结构'||val=='其他'){
			useOptions.value = [
            {
                value: '第Ⅰ类',
                label: '第Ⅰ类',
                children: [
                    {
                        value: '住宅',
                        label: '住宅'
                    },
                    {
                        value: '其他人员居住场所',
                        label: '其他人员居住场所'
                    }
                ]
            },
            {
                value: '第Ⅲ类',
                label: '第Ⅲ类',
                children: [
                    {
                        value: '除I、II类以外',
                        label: '除I、II类以外'
                    }
                ]
            }
        ]
		if(val=='土木结构'){
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>item.value=='未设防');
		yearsOptions.value = dictStore.yearsOptions.filter((item, index) => index < 4);
		// 切换类型时，年代--选项，则清空
		if (params.value.years == '2010-2016年'||params.value.years == '2016年以后') {
			params.value.years = ''
		}
		}else if(val=='其他'){
			fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value=='未设防'||item.value=='自设防'||item.value=='6度'));
		}
	}else{
			useOptions.value = [
            {
                value: '第Ⅱ类',
                label: '第Ⅱ类',
                children: [
                    {
                        value: '生产车间',
                        label: '生产车间'
                    },
                ]
            },
        ]
		}
	}
};

// 用途选择
const useChange = val => {
	const use = useOptions.value.find(item => item.value === val);
	if (use) {
		params.value.purpose1 = '';
		use1Options.value = use.children;
	}
};

//表格
const multipleTableRef = ref();
// 表格多选
const handleSelectionChange = val => {
	multipleSelection.value = val;
	curTableRow.value = val[0];
};
// 表格行点击事件
const rowClick = (row, column, event) => {
	// 设置选中效果
	multipleTableRef?.value?.toggleRowSelection(row);
};
// 点击编号跳转至此数据的详细信息界面
const viewProject = row => {
	router.push({
		path: '/buildingVulnerAnalysis/seismicVulnerAnalysis/seismicDetailsInterface',
		// 路由参数
		query: { id: row.cpviId,isView:true,calculateOrNot:row.calculateOrNot },
	});
};
//是否移出管理库
const handleRemove = (row) => {
	if (row.cpviId) {
		moveBasicLibraryApi({
			//...params.value
			// dataType: row.dataType
			id: row.cpviId,
			// number: row.number
			operate:row.basicLibrary,
			operate: 1,
			structureType: row.structureType0,
			structureType1: row.structureType1,
			fortification: row.fortification,
			years: row.years,
			use0: row.purpose0,
			use1: row.purpose1,
			province: row.province,
			city: row.city,
			county: row.county,
			cs: row.cs
		}).then((res) => {
			if (res.code === 200) {
				console.log(res)
				ElMessage({
					type: 'success',
					message: '成功!'
				});
				proxy.$modal.msgSuccess("成功");
				onSearch();
			}
		}).catch(err => {
			console.log(err);
			proxy.$modal.msgError(`失败`);
		});
	}
}

// 分页
// 每页显示多少行
const handleSizeChange = val => {
	// 改变每页显示的条数
	queryPagination.value.pageSize = val;
	// 注意：在改变每页显示的条数时，要将页码显示到第一页
	queryPagination.value.pageNo = 1;
	onSearch();
};
// 当前页数
const handleCurrentChange = val => {
	queryPagination.value.pageNo = val;
	onSearch();
};

// 查询
const onSearch = () => {
	queryCpvAnalysisApi({
		...params.value,
		page: queryPagination.value.pageNo,
		rows: queryPagination.value.pageSize
	}).then(res => {
		if (res.code === 200 && res.data) {
			// 分页总数
			queryPagination.value.total = res.data.total || 0;
			tableData.value = res.data.rows && res.data.rows.length ? res.data.rows : [];
		} else {
			// 分页总数
			queryPagination.value.total = 0;
			tableData.value = [];
		}
	}).catch(err => {
		console.log(err);
	});
};

//重置
const onRest = () => {
	proxy.resetForm('queryRef');
	onSearch();
};

// //导入
// const onImport = () => {
// 	router.push({ path: '/disasterDataManagement/importData/buildingDamageData' });
// };
// //修改
// const onModify = (row) => {
//     router.push({ path: '', query: { id: 'modify', type: row.type } })
// }
// //删除
// const onDelete = row => {
// 	console.log(row);
// 	const query = { number: row.number };
// 	deleteBuildingsById(query)
// 		.then(res => {
// 			if (res.code === 200) {
// 				console.log(res);
// 				proxy.$modal.msgSuccess('删除成功');
// 				onSearch();
// 			}
// 		})
// 		.catch(err => {
// 			console.log(err);
// 		});
// };

onMounted(() => {
	// 初始化获取数据
	onSearch();
	// 获取行政区划数据
	getProvinceData();
});
</script>

<style lang="scss" scoped>
.table-wrapper {
	position: relative;

	h4 {
		font-size: 16px;
		font-weight: bold;
		color: #107ce5;
		text-align: center;
	}
}

.paging {
	padding: 20px 0;
}

.form-inline {
	.el-form-item {
		margin-right: 0;
	}
}
</style>
